#include <g-bios.h>
#include <sysconf.h>
#include <core/getopt.h>


static int atoh_ex(BYTE *pMac, const char *pStr, int nLen)
{
	int i;
	BYTE nVal = 0;
	const char *pTmp;

	for (i = 0, pTmp = pStr; i < nLen; i++, pTmp++)
	{
		nVal = nVal << 4;

		if (*pTmp >= '0' && *pTmp <= '9')
		{
			nVal |= *pTmp - '0';
		}
		else if (*pTmp >= 'a' && *pTmp <= 'f')
		{
			nVal |= (*pTmp - 'a') + 10;
		}
		else if(*pTmp >= 'A' && *pTmp <= 'F')
		{
			nVal |=  *pTmp - 'A' + 10;
		}
		else
		{
			return -1;	
		}
	}

	*pMac = nVal;

	return i;
}


static int StrToMac(BYTE *pbMAC, const char *pStr)
{
	int i;
	const char *pNext;



	if (NULL == pStr)
		return -EINVAL;

	for (i = 0, pNext = pStr; i < 6; pNext++)
	{		
		if (':' == *pNext)
		{
			atoh_ex((pbMAC + i++), pStr, pNext - pStr);
	
			pStr = ++pNext;

			if (i >= 6)
				return -EINVAL;
		}
		else if ('\0' == *pNext)
		{
			atoh_ex((pbMAC + i++), pStr, pNext - pStr);
	
			pStr = ++pNext;

			break;
		}
	}

	if (i < 6)
		return -EINVAL;
	else 
		return 0;

}


static int ShowNetInfo(void *pParam)
{
	BYTE bLocal[IPV4_ADDR_LEN], bServer[IPV4_ADDR_LEN];
	BYTE vbRealMac[MAC_ADDR_LEN];


	GuNetGetIP(NULL, (UINT32 *)bLocal);

    printf("\nlocal  addr: %d.%d.%d.%d\n",
		bLocal[0],
		bLocal[1],
		bLocal[2],
		bLocal[3]
		);


	GuNetGetTftpSvr((UINT32 *)bServer);
		  
    printf("server addr: %d.%d.%d.%d\n",
		bServer[0],
		bServer[1],
		bServer[2],
		bServer[3]
		);


	GuNetGetMac(NULL, vbRealMac);

	printf("MAC addr: %02x:%02x:%02x:%02x:%02x:%02x\n",
		vbRealMac[0],
		vbRealMac[1],
		vbRealMac[2],
		vbRealMac[3],
		vbRealMac[4],
		vbRealMac[5]
	);
}


static void ShowUsage(void)
{
	printf("Usage:ifconfig [-l <local_addr>] [-s <serv_addr>] [-m <mac_addr>]\n");
}


static int main(int argc, char *argv[])
{
	int i, ret = 0;
	BYTE pbMacTmp[6];
	UINT32 dwLocaIP, dwSvrIP;
	BYTE bSvrIP[IPV4_ADDR_LEN];
	int opt;
	char *arg;


	while ((opt = getopt(argc, argv, "l:s:m:h", &arg)) != -1)
	{
		switch (opt)
		{
		case 'l':
			if (GuStrToIp((BYTE *)&dwLocaIP, arg))
			{
				printf("Set Local IP Error! \nUsage: ifconfig -l <IP Address>\n");
				return -EINVAL;
			}

			GuNetSetIP(NULL, dwLocaIP);

			break;
		
		case 's':
			if (GuStrToIp((BYTE *)&dwSvrIP, arg))
			{
				printf("Set Server IP Error! \nUsage: ifconfig -s <IP Address>\n");
				return -EINVAL;
			}

			GuNetSetTftpSvr(dwSvrIP);

			break;

		case 'm':
			if (StrToMac(pbMacTmp, arg))
			{
				printf("Set Mac Error! \nUsage: ifconfig -m <Mac Address>\n");
				return -EINVAL;
			}

			GuNetSetMac(NULL, pbMacTmp);

			break;

		case ':':
		case '?':
			printf("Try `%s -h` for more information.\n",argv[0]);
			//fixme
			return -1;

		case 'h':
		default:
			ShowUsage();
			//fixme
			return -1;
		}
	}

	ShowNetInfo(NULL);

	if (argc > 1)
		ret = GuSysConfStore();

	//fixme
	return ret;
}

INSTALL_APPLICATION(ifconfig, main, "Configure etwork interface.");

